//
//  PlaySoundTool.m
//  Unity-iPhone
//
//  Created by Kin Kwan Pan on 2017/7/8.
//
//

#import "PlaySoundTool.h"

@interface PlaySoundTool()

@property (nonatomic, strong)NSURL *fileURL;
@property (nonatomic, assign)SystemSoundID soundID;

@end

@implementation PlaySoundTool

- (id)initForPlayingVibrate {
    self = [super init];
    if (self) {
        _soundID = kSystemSoundID_Vibrate;
    }
    return self;
}
//获取设备状态，是否插入耳机，如果插入耳机，则返回“YES"
+ (BOOL)isHeadSetPlugging {
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
            return YES;
    }
    return NO;
}

- (id)initForPlayingSystemSoundEffectWith:(NSString *)resourceName ofType:(NSString *)type {
    self = [super init];
    if (self) {
        NSString *path = [[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:resourceName ofType:type];
        if (path) {
            SystemSoundID theSoundID;
            OSStatus error =  AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &theSoundID);
            if (error == kAudioServicesNoError) {
                _soundID = theSoundID;
            } else {
                NSLog(@"创建音效失败");
            }
        } else {
            NSLog(@"路径无效");
        }
    }
    return self;
}

- (id)initForPlayingSoundEffectWith:(NSString *)filename {
    self = [super init];
    if (self) {
        self.fileURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
        if (_fileURL) {
            SystemSoundID theSoundID;
            OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)_fileURL, &theSoundID);
            if (error == kAudioServicesNoError) {
                self.soundID = theSoundID;
            } else {
                NSLog(@"创建音效失败");
            }
        } else {
            NSLog(@"路径无效");
        }
    }
    return self;
}

- (void)play {
    AudioServicesAddSystemSoundCompletion(_soundID, NULL, NULL, &playFinished, (__bridge void *)(self));
    AudioServicesPlaySystemSound(self.soundID);
}

void playFinished(SystemSoundID ssID, void* clientData) {
    // 移除完成后执行的函数
    AudioServicesRemoveSystemSoundCompletion(ssID);
    NSLog(@"移除");
}

- (void)dealloc {
    // 根据ID释放自定义系统声音
    AudioServicesDisposeSystemSoundID(_soundID);
    NSLog(@"释放");
}

@end
